<template>
  <div id="app">
    <el-row>
      <el-col :span="24">
        <el-form ref="ruleForm" :model="baseTable.sel" :rules="baseTable.rules">
          <el-table :data="tableData" highlight-current-row style="width: 100%;">
            <!-- <el-table-column type="index"></el-table-column> -->
            <el-table-column v-for="(item,index) in baseTable.columns" :key="index" :label="item.label"
                             :prop="item.prop" :width="item.width"
            >
              <template slot-scope="scope">
                <!--编辑状态-->
                <el-form-item v-if="scope.row.isSet" :prop="item.prop">
                  <el-input v-if="item.type === 'INPUT'" v-model="baseTable.sel[item.prop]"
                            :placeholder="`请输入${item.label}`"
                            size="small"
                  >
                    <template v-if="item.append" slot="append">{{ item.append }}</template>
                  </el-input>
                  <el-select v-if="item.type === 'SELECT'" v-model="baseTable.sel[item.prop]"
                             :placeholder="`请选择${item.label}`"
                             size="small" style="width:100%;"
                  >
                    <el-option
                      v-for="dict in item.typeOptions"
                      :key="dict.dictValue"
                      :label="dict.dictLabel"
                      :value="dict.dictValue"
                    />
                  </el-select>
                  <el-date-picker v-if="item.type === 'DATE'" v-model="baseTable.sel[item.prop]" placeholder="请选择日期"
                                  size="small"
                                  style="width:100%" type="date" value-format="yyyy-MM-dd"
                  />
                  <el-date-picker v-if="item.type === 'DATETIME'" v-model="baseTable.sel[item.prop]" placeholder="请选择日期"
                                  size="small"
                                  style="width:100%" type="month" value-format="yyyy-MM" :picker-options="daterangeOptions"
                  />
                  <el-date-picker
                      v-if="item.type === 'DATERANGE'" v-model="baseTable.sel[item.prop]"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      value-format="yyyy-MM-dd"
                      >
                    </el-date-picker>
                  <attachment v-if="item.type === 'UPLOAD'" :ref="item.prop" v-model="baseTable.sel[item.prop]"
                              :limit="1"
                              :upload-size-limit="150"
                              module-name="上传扫描件"
                              @onFileSuccess="onFileSuccess(arguments, item)"
                  />
                </el-form-item>
                <!--显示状态-->
                <div v-else>
                  <span v-if="item.type === 'SELECT'"
                  >{{ dictLabelFormat(item.typeOptions, scope.row[item.prop]) }}</span>
                  <el-tag v-if="item.type === 'STATUS'">{{ scope.row[item.prop] }}</el-tag>
                  <attachment v-if="item.type === 'UPLOAD'"
                              :limit="1"
                              :upload-size-limit="150"
                              module-name="上传扫描件"
                              :hidden="true"
                              :archive-id="scope.row.id"
                              v-model="scope.row.id"
                              :disabled="true"
                  />
                  <el-button
                    v-if="item.type === 'BTN'"
                    icon="el-icon-edit-outline"
                    size="mini"
                    type="text"
                    @click="handleBtn(scope.row)"
                  >录入
                  </el-button>
                  <span v-if="item.type === 'DATERANGE'">{{scope.row[item.prop][0] + '至' + scope.row[item.prop][1]}}</span>
                  <span
                    v-if="item.type !== 'SELECT' &&item.type !== 'STATUS' && item.type !== 'UPLOAD' && item.type !== 'BTN' && item.type !== 'DATERANGE'"
                  >{{ scope.row[item.prop] }}<span>{{item.append ? '%':''}}</span></span>
                </div>
              </template>
            </el-table-column>
            <el-table-column class-name="col-decoration" label="操作" width="180" v-if="editable">
              <template slot-scope="scope">
                <el-button
                  v-if="scope.row.isSet"
                  icon="el-icon-finished"
                  size="mini"
                  type="text"
                  @click.stop="saveRow(scope.row, scope.$index)"
                >保存
                </el-button>
                <el-button
                  v-if="scope.row.isSet"
                  icon="el-icon-close"
                  size="mini"
                  type="text"
                  @click="cancelEdit(scope.row, scope.$index)"
                >取消
                </el-button>
                <el-button
                  v-if="!scope.row.isSet"
                  icon="el-icon-edit"
                  size="mini"
                  type="text"
                  @click="editRow(scope.row, scope.$index)"
                >编辑
                </el-button>
                <el-button
                  v-if="!scope.row.isSet"
                  icon="el-icon-delete"
                  size="mini"
                  type="text"
                  @click="deleteRow(scope.$index)"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </el-col>
      <el-col :span="24">
        <div v-if="editable" class="el-table-add-row" @click="add()"><span>+ 添加</span></div>
      </el-col>
    </el-row>
    <!-- <span>{{baseTable.data}}</span> -->
  </div>
</template>

<script>
import Attachment from '@/components/ScAttachment'

export default {
  name: 'BaseTable',
  props: {
    columns: {
      required: true,
      type: Array,
      default: () => [
        {
          prop: 'name',
          label: '名称',
          type: 'INPUT',
          width: 200
        },
        {
          prop: 'info',
          label: '其他信息',
          type: 'SELECT',
          typeOptions: []
        }
      ]
    },
    parentId: {
      required: false,
      type: Number,
      default: -1
    },
    data: {
      required: true,
      type: Array,
      default: () => []
    },
    // form: {
    //   required: true,
    //   type: Object,
    //   default: () => ({
    //     name: '',
    //     info: ''
    //   })
    // },
    rules: {
      required: true,
      type: Object,
      default: () => ({
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        info: [{ required: true, message: '其他信息不能为空', trigger: 'blur' }]
      })
    },
    propsSave: {
      type: Function,
      default: () => {
        return Function
      }
    },
    propsDelete: {
      type: Function,
      default: () => {
        return Function
      }
    },
    propsGetInfo: {
      type: Function,
      default: () => {
        return Function
      }
    },
    propsInit: {
      type: Function,
      default: () => {
        return Function
      }
    },
    editable:{
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      pickerOptions: {
        disabledDate (time) {
          // 禁用之前的时间
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
        },
      },
      daterangeOptions:{
        disabledDate (time) {
          // 禁用以后的时间
          return time.getTime() > Date.now() - 8.64e6
        },
      },
      baseTable: {
        sel: undefined, //选中行
        columns: this.columns,
        data: this.data,
        rules: this.rules
      }
    }
  },
  computed: {
    tableData() {
      return this.data.map(element => {
        this.$set(element, 'isSet', false)
        return element
      })
    }
  },
  methods: {
    add() {
      for (let rowData of this.tableData) {
        if (rowData.isSet) return this.$message.warning('请先保存当前编辑项')
      }
      let newRowData = {
        'isSet': true
      }
      this.tableData.push(newRowData)
      this.baseTable.sel = JSON.parse(JSON.stringify(newRowData))
    },
    //保存
    saveRow(row, index) {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          let selectedRowData = JSON.parse(JSON.stringify(this.baseTable.sel))
          for (let p in selectedRowData) {
            row[p] = selectedRowData[p] //将sel里面的value赋值给这一行
          }
          this.propsSave(row).then((response) => {
            if(response) {
              if (response.code === 200) {
                this.msgSuccess('保存成功')

                row.isSet = false
                // row.id = response
                // this.propsInit();
                this.reload()
              } else {
                this.msgError(response.msg)
              }
            }
          })
        } else {
          console.log('验证不通过')
          return false
        }
      })
    },
    //编辑
    editRow(row) {
      for (let rowData of this.tableData) {
        if (rowData.isSet) return this.$message.warning('请先保存当前编辑项')
      }
      this.baseTable.sel = row
      row.isSet = true
    },
    //取消编辑
    cancelEdit(row, index) {
      if (row && row.id) {
        this.$refs['ruleForm'].resetFields()
        row.isSet = false
      } else {
        this.tableData.splice(index, 1)
      }
    },
    //删除
    deleteRow(index) {
      let rowData
      if (index >= 0 && index < this.tableData.length) {
        rowData = this.tableData[index]
      }
      this.propsDelete(rowData.id).then(response => {
        if (response.code === 200) {
          this.msgSuccess('删除成功')
          rowData.isSet = false
          this.tableData.splice(index)
          this.reload()
        } else {
          this.msgError(response.msg)
        }
      })
    },
    onFileSuccess(fileIds,item) {
      this.baseTable.sel[item.prop] = fileIds[0]
    },
    handleBtn(row) {
      this.$emit('handleBtn', row)
    },
    //根据字典值格式化为字典标签
    dictLabelFormat(options, selectedValue) {
      return this.selectDictLabel(options, selectedValue)
    },
    //重新加载
    reload() {
      if (this.parentId && this.parentId !== -1) {
        this.propsInit(this.parentId)
      } else {
        this.propsInit()
      }
    }
  },
  components: { Attachment }
}
</script>

<style lang="scss" scoped>
.el-table-add-row {
  margin-top: 10px;
  width: 100%;
  height: 34px;
  border: 1px dashed #DCDFE6;
  border-radius: 3px;
  cursor: pointer;
  justify-content: center;
  display: flex;
  align-items: center;
}
::v-deep .el-form-item {
  margin-bottom: 20px;
}
::v-deep .el-form-item.is-error {
  margin-bottom: 20px;
}
</style>
